package com.iuhao.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by yanhao on 2018/11/2.
 */
@Configuration
public class GlobalRouteFilter implements GlobalFilter, Ordered {
    private static final Logger logger = LoggerFactory.getLogger(GlobalRouteFilter.class);

    private static final String COUNT_Start_TIME = "countStartTime";

    /**
     * 全局过滤器
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest.Builder builder = exchange.getRequest().mutate();
        builder.header("GlobalFilter", "GlobalFilter success");
        chain.filter(exchange.mutate().request(builder.build()).build());
        //TODO 统一网关日志处理（走网关的服务都会走的日志 -->可以做统一的鉴权 ）
        ServerHttpRequest request = exchange.getRequest();
        logger.info("请求方法 :" + exchange.getRequest().getMethod());
        logger.info("请求url :" + exchange.getRequest().getURI());
        logger.info("请求RemoteAddress :" + exchange.getRequest().getRemoteAddress());
        logger.info("请求body :" + exchange.getRequest().getBody());

        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    Long startTime = exchange.getAttribute(COUNT_Start_TIME);
                    Long endTime = (System.currentTimeMillis() - startTime);
                    if (startTime != null) {
                        logger.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                    }
                })
        );
        //return chain.filter(exchange.mutate().request(builder.build()).build());
    }

    @Override
    public int getOrder() {
        return -200;
    }
}
